package com.lam.common.components.redis.writer;

import java.time.Duration;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.util.Assert;

/**
 * 该类参照 DefaultRedisCacheWriter 重写了 remove 方法实现通配符*删除
 */
public class LamRedisCacheWriter extends DefaultRedisCacheWriter {
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public LamRedisCacheWriter(RedisConnectionFactory connectionFactory) {
    	super(connectionFactory);
    }

    public LamRedisCacheWriter(RedisConnectionFactory connectionFactory, Duration sleepTime) {
        super(connectionFactory, sleepTime);
    }
    
    public void remove(String name, byte[] key) {
        Assert.notNull(name, "Name must not be null!");
        Assert.notNull(key, "Key must not be null!");
        String keyString = new String(key);
        logger.info("redis remove key:{}", keyString);
        if(keyString!=null && keyString.endsWith("*")){
            execute(name, connection -> {
                // 获取某个前缀所拥有的所有的键，某个前缀开头，后面肯定是*
                Set<byte[]> keys = connection.keys(key);
                int delNum = 0;
                for (byte[] keyByte : keys) {
                    delNum += connection.del(keyByte);
                }
                return delNum;
            });
        }else{
            this.execute(name, (connection) -> {
                return connection.del(new byte[][]{key});
            });
        }
    }

}
